<template>
  <Card>
    <div slot="title" align="center">
      <Button type="text" size="small" @click="backClick" style="float: left">
        <Icon type="ios-arrow-back" style="margin-right: 5px"></Icon>
        返回
      </Button>

      <h4>管理主题</h4>
    </div>

    <div class="body">

      <div>
        <Button type="ghost" @click="modal = true">
          <Icon type="ios-plus-empty"></Icon>
          添加文章
        </Button>
        <Button type="info" @click="setHotEvent">{{subject.top?'取消置顶':'推荐此主题'}}</Button>
        <Tag style="margin-left: 10px" color="blue">文章数： {{subject.size}}</Tag>
        <Tag v-if="subject.top" style="margin-left: 10px" color="green">推荐主题</Tag>
      </div>

      <div style="margin-top: 30px">
        <span style="margin-right: 10px;font-size: 11px;color: #80848f;">更新</span>
        <i-switch v-model="showUpdate">
          <span slot="open">开</span>
          <span slot="close">关</span>
        </i-switch>
      </div>

      <transition name="fade">
        <div v-if="showUpdate">
          <div style="margin-top: 30px">
            <p style="margin-bottom: 6px;font-size: 11px">标题</p>
            <Input type="text" v-model="subject.title" style="width: 200px;"/>
          </div>

          <div style="margin-top: 10px">
            <p style="margin-bottom: 6px;font-size: 11px">描述</p>
            <Input type="textarea" v-model="subject.detail" style="width: 300px;"/>
            <br/><br/>

          </div>
          <div style="margin-top: 10px">
            <p style="margin-bottom: 6px;font-size: 11px">主图</p>
            <img class="mainPic" :src="subject.mainimg"/>
            <my-upload @onSuccess="uploadSuccess"></my-upload>
            <Button type="primary" @click="updateSub">更新</Button>
          </div>
        </div>
      </transition>

      <Table style="margin-top: 30px;overflow: hidden" :loading="loading" stripe :columns="columns"
             :data="data"></Table>

      <div style="margin: 10px;overflow: hidden">
        <br/>
        <div align="center">
          <Page :page-size="pageConfig.size" :total="pageConfig.total" :current="pageConfig.currentPage"
                @on-change="changePage"></Page>
        </div>
      </div>
    </div>
    <Modal
      v-model="modal"
      width="60%"
      @on-ok="okSelectedArticle"
      title="添加文章">
      <select-article ref="selectedDat"></select-article>
    </Modal>

  </Card>
</template>

<script>
  import selectArticle from './public/custom/SelectArticle';
  import MyUpload from '@/components/public/custom/ImgUpload.vue';

  export default {
    name: "SubjectManage",
    components: {
      selectArticle,
      MyUpload
    },
    data() {
      return {
        showUpdate: false,
        modal: false,
        loading: false,
        id: -1,  //传入进来的ID
        subject: {},  //服务器获取的Subject对象
        columns: [
          {
            title: '序号',
            type: 'index'
          },
          {
            title: '标题',
            key: 'title',
            ellipsis: true
          },
          {
            title: '创建时间',
            key: 'createTime',
            sortable: true
          },
          {
            title: '操作',
            render: (h, params) => {
              return h('Button', {
                props: {
                  type: 'error'
                },
                on: {
                  click: () => {
                    let id = this.data[params.index].id;
                    console.log(id + " id");
                    let list = this.subject.articlelist;
                    console.log("Old:" + list);
                    let index;
                    for (let i = 0; i < list.length; i++) {
                      if (list[i] == id) {
                        index = i;
                        break;
                      }
                    }
                    list.splice(index, 1);
                    console.log("newList:" + list);

                    //进行保存操作了
                    this.axios.post(this.baseUrl+'/update-subject',
                      JSON.stringify({
                        id: this.id,
                        articlelist: list
                      }), {
                        headers: {"Content-Type": "application/json"}
                      }).then(res => {
                      let data = res.data;
                      if (data.code != 0) {
                        this.$Message.success('删除成功!');
                        this.init();
                      } else {
                        this.$Message.error(data.msg);
                      }
                    }).catch(error => {
                      this.$Message.error('服务器异常: ' + error.status);
                    })
                  }
                }
              }, "删除")
            }
          }
        ],
        data: [],
        pageConfig: {
          size: 6,
          total: 0,
          currentPage: 1
        }
      }
    },
    created() {
      this.id = this.$route.params.id;
      this.init();
    },
    methods: {
      backClick() {
        this.$router.push({name: 'Subject'});
      },
      changePage(page) {
        this.request(page);
      },
      request(page) {
        if (this.subject.articlelist.length == 0) {
          return;
        }
        this.data.length = 0;
        this.loading = true;
        this.http.post('/get-article-ids', {
          isSplit: true,
          page: page,
          size: this.pageConfig.size,
          ids: JSON.stringify(this.subject.articlelist)
        }, data => {
          let list = data.list;
          this.pageConfig.total = data.total;
          this.pageConfig.currentPage = data.pageNum;
          list.forEach(item => {
            this.data.push({
              title: item.article.title,
              createTime: item.article.createtime,
              id: item.article.id
            });
          })
        }, error => {
          this.$Message.error(error);
        })
        this.loading = false;
      },
      init() {  //第一次初始化数据
        this.http.get('/get-subject-id', {id: this.id},
          data => {
            this.subject = data;
            this.subject.articlelist = JSON.parse(data.articlelist);
            this.subject.size = this.subject.articlelist.length;
            this.request(1);
          }, error => {
            this.$Message.error(error);
          })
      },
      setHotEvent() {
        this.http.postJson('/update-subject', {
          id: this.id,
          top: !this.subject.top
        }, data => {
          this.$Message.success("设置成功");
          this.init();
        }, error => {
          this.$Message.error(error);
        })
      },
      updateSub() {
        if (this.subject.title.length != 0 &&
          this.subject.detail.length != 0 && this.subject.mainimg.length != 0) {
          let data = {
            id: this.id,
            title: this.subject.title,
            detail: this.subject.detail,
            mainimg: this.subject.mainimg
          };
          this.http.postJson('/update-subject', data, data => {
            this.$Message.success("更新成功");
            this.showUpdate = false;
            this.init();
          }, error => {
            this.$Message.error(error);
          })
        } else {
          this.$Message.error("请输入完整");
        }

      },
      okSelectedArticle() {
        let list = this.$refs.selectedDat.selectedList;
        let dat = this.subject.articlelist;
        list.forEach(item => {
          let isAdd = true;
          dat.forEach(it => {
            if (it == item.id) {
              isAdd = false;
            }
          });
          if (isAdd) {
            dat.push(item.id);
          }
        });
        this.http.postJson('/update-subject', {
          id: this.id,
          articlelist: this.subject.articlelist
        }, data => {
          this.$Message.success("添加成功");
          this.showUpdate = false;
          this.init();
        }, error => {
          this.$Message.error(error);
        })
      },
      uploadSuccess(url) {  //图片上传成功的回调
        this.subject.mainimg = url;
      }
    }
  }
</script>

<style lang="stylus" scoped>
  .body
    margin: 10px
    .mainPic
      max-height: 200px
</style>


